<template>
  <!-- 创建独立产品、 -->
  <el-card>
    <div>
      <template v-if="!showModel">
        <div class="flexbox_row">
          <div class="flex1">
            <el-row>
              <el-col :span="24">
                <el-form :inline="true" :model="searchInfo">
                  <el-form-item label="SKU:" class="mb0">
                    <el-input
                      v-model.trim="searchInfo.sku"
                      maxlength="50"
                      clearable
                      class="w200px"
                      placeholder="输入关键字查询"
                    />
                  </el-form-item>
                  <el-form-item class="mleft10 mb0" label="产品名称:">
                    <el-input
                      v-model.trim="searchInfo.name"
                      maxlength="50"
                      clearable
                      class="w200px"
                      placeholder="输入关键字查询"
                    />
                  </el-form-item>

                  <el-form-item label="创建时间:" prop="times" class="mb0">
                    <!-- <span>创建时间：</span> -->
                    <el-date-picker
                      v-model="searchInfo.times"
                      type="datetimerange"
                      range-separator="-"
                      class="w350px"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      @change="searchInfo.times = $changeTime($event)"
                    ></el-date-picker>
                  </el-form-item>

                  <el-form-item class="mb0" label="状态:">
                    <el-select v-model="searchInfo.is_approval" placeholder="请选择">
                      <el-option label="已审核" :value="2"></el-option>
                      <el-option label="待审核" :value="1"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item class="mb0">
                    <el-button type="primary" icon="el-icon-search" @click="getListDataHandler">查询</el-button>
                    <el-button type="warning" icon="el-icon-delete" @click="clearSearch">清空</el-button>

                    <el-dropdown class="mleft10" trigger="click" :disabled="exportXSLing" @command="OtherFu">
                      <el-button type="primary" plain>
                        其他功能<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="export" icon="el-icon-download">导出</el-dropdown-item>
                        <el-dropdown-item command="upload" icon="el-icon-upload2">导入</el-dropdown-item>
                        <el-dropdown-item command="editable" icon="el-icon-edit">操作列表</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </div>

          <div class="addbox">
            <el-button type="success" size="default" @click="addModal('add')" icon="el-icon-plus"
              >创建单个产品</el-button
            >
          </div>
        </div>

        <el-main style="padding: 0 !important">
          <div class="wh100">
            <el-table
              :data="tableDataList"
              stripe
              v-loading="loadings"
              border
              highlight-current-row
              class="wh100"
              tooltip-effect="dark"
              :height="tabelHeight(335)"
              ref="multipleTable"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                v-for="(item, index) in tableColumn"
                :key="index"
                :width="item.width || ''"
                :type="item.type || ''"
                :prop="item.key || ''"
                header-align="center"
                align="center"
                show-overflow-tooltip
                :fixed="item.fixed || false"
                :sortable="item.sortable || ''"
                :label="item.title || ''"
                :minWidth="item.minWidth || ''"
                :filter-method="item.filterRender"
                :index="item.index"
              >
                <!-- :selectable="isSelectChange" -->
                <template #default="scope" v-if="item.type !== 'selection' && item.type !== 'index'">
                  <template v-if="item.render">
                    <cl-expand :column="item" :row="scope.row" :render="item.render" :index="index" />
                  </template>

                  <template v-else-if="item.type !== 'selection'">
                    <span>{{ scope.row[item.key] || '' }}</span>
                  </template>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="scope">
                  <!-- <el-dropdown trigger="click"
                               size="medium"
                               split-button
                               type="primary"
                               @command="changeEdit($event, scope.row)">
                    操作
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item icon="el-icon-edit"
                                        command="edit">修改</el-dropdown-item>
                      <el-dropdown-item icon="el-icon-delete"
                                        command="delete"
                                        :disabled="scope.row.status == 2">作废</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->

                  <el-button type="primary" icon="el-icon-edit" @click="changeEdit('edit', scope.row)">修改</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    :disabled="scope.row.status == 2"
                    @click="changeEdit('delete', scope.row)"
                    >作废</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>

        <el-footer class="footsPadding0 flex_row_space-between">
          <div class="foot-operation">
            <el-button size="medium" type="primary" @click="dialogVisible = true" :disabled="!selectIds.length"
              >批量审核</el-button
            >
            <el-button
              size="medium"
              class="mleft10"
              type="danger"
              icon="el-icon-delete"
              @click="toVoid"
              :disabled="!selectIds.length"
              >批量作废</el-button
            >

            <el-button size="medium" class="mleft10" type="success" @click="PrintBarcode" :disabled="!selectIds.length"
              >打印条形码</el-button
            >
          </div>

          <div>
            <cl-pagination :paging-info="pagingInfo" @size_current_change="sizeCurrentChange" />
          </div>
        </el-footer>
      </template>

      <add-model v-else :info-model="rowData" :show-model="showModel" @close="addModal"></add-model>

      <dialog-modal :show-modal.sync="dialogVisible" @success="toExamineHandler" @close="dialogVisible = false" />

      <upload :show-modal.sync="showUpload" @get-data="getListDataHandler" />

      <edit-table :show-modal.sync="showEditTable" @get-data="sortChange" />

      <bar-code :show-modal.sync="showBarCode" :select-data="selectIds"></bar-code>
    </div>
  </el-card>
</template>

<script>
import { columnsTitle } from './column.js'
import ProductApi from '@/api/product.js'
import { getTruthyParams, dowloadFileResFunction } from '@/libs/common.js'
import mixins from '@/component-cl/mixins/mixins'
import ClExpand from '@/component-cl/expand/expand'

export default {
  name: 'Independent',
  mixins: [mixins],

  components: {
    ClExpand,
    dialogModal: () => import('@/component-cl/dialog/dialog.vue'),
    BarCode: () => import('./bar-code.vue'),
    EditTable: () => import('./edi-table.vue'),
    AddModel: () => import('./add-info.vue'),
    Upload: () => import('./upload.vue'),
  },

  data() {
    return {
      cloumnArr: columnsTitle(this),
      dialogVisible: false,
      showEditTable: false,
      showModel: false,
      showBarCode: false,
      rowData: {},
      exportXSLing: false,
      showUpload: false,
      selectIds: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
    }
  },

  computed: {
    tableColumn() {
      let list = this.cloumnArr
      list = list.filter(e => !e.hide)
      console.log(list, '========')
      return list
    },
  },

  methods: {
    // isSelectChange (e) {
    //   if (e.status == 1) {
    //     return true
    //   }
    //   return false
    // },
    sortChange() {
      this.cloumnArr = this.cloumnArr.map(ele => {
        if (ele.hide) {
          ele.hide = false
        }
        return ele
      })

      console.log(this.cloumnArr, '========ele')
    },

    handleDateChange(date) {
      console.log(date, '=========')
    },
    /**
     * 导出
     */
    async confirmExport() {
      try {
        this.exportXSLing = true
        const RES = await ProductApi.exportProductFile(1)
        console.log(RES, '================')

        dowloadFileResFunction({ file: RES, fileName: '单个产品数据', status: RES ? 200 : 404 })
        this.exportXSLing = false
      } catch (error) {
        this.exportXSLing = false

        this.$message({
          message: '网络异常/导出失败',
          type: 'warning',
        })
      }
    },

    async PrintBarcode() {
      this.showBarCode = true
      // try {
      //   const RES = await ProductApi.PrintBarcodeHandler({ ids: this.selectIds })
      //   console.log(RES, '=============')
      // } catch (error) {
      //   console.log(error)
      // }
    },

    /**
     * 作废
     */
    toVoid(data = false) {
      const selectIds = []
      this.selectIds.forEach(ele => {
        if (ele.status == 1) {
          selectIds.push(ele.id)
        }
      })

      let msg = '确定作废已勾选产品吗？'
      if (data && data.id) {
        msg = `确定作废 ${data.name} 此产品吗？`
      }
      this.$confirm(msg, '温馨提示', {
        confirmButtonText: '作废',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          let ids = []
          let res = null
          if (data && data.id) {
            ids = [data.id]
          } else {
            ids = selectIds
          }
          res = await ProductApi.deleteProduct(ids)

          console.log(res)
          if (res.code == 3) {
            this.$message({
              message: '成功',
              type: 'success',
            })
            this.getListDataHandler()
          } else {
            this.$message({
              message: '失败',
              type: 'warning',
            })
          }
        } catch (error) {
          this.$message({
            message: '网络异常/失败',
            type: 'warning',
          })
        }
      })
    },

    /**
     *审核
     */
    async toExamineHandler(type) {
      const selectIds = []
      this.selectIds.forEach(ele => {
        selectIds.push(ele.id)
      })
      try {
        const params = {
          ids: selectIds,
          status: type,
        }
        const RES = await ProductApi.productToExamine(params)
        console.log(RES)
        if (RES.code == 2) {
          this.$message({
            message: '成功',
            type: 'success',
          })
          this.dialogVisible = false

          this.getListDataHandler()
        } else {
          this.$message({
            message: '失败',
            type: 'warning',
          })
        }
      } catch (error) {
        this.dialogVisible = false
        this.$message({
          message: '网络异常/失败',
          type: 'warning',
        })
      }
    },

    // 多选操作
    handleSelectionChange(e) {
      console.log(e, '=======')
      this.selectIds = e
      // if (e && e.length) {
      //   e.forEach(ele => {
      //     this.selectIds.push(ele.id)
      //   })
      // }
    },

    // 新增
    addModal(type = false) {
      console.log(type, '=======', this.pagingInfo)
      if (type === 'close') {
        this.showModel = false
        this.getListDataHandler()
      } else {
        this.rowData = {
          isAdd: 'add',
          category_id: [],
          product_barcodes: [{ custom_code_name: '', custom_code: '' }],
          shops: [{ shop_sku: '', shop_code: '' }],
        }

        this.showModel = true
      }
    },

    async changeEdit(e, data) {
      console.log(e, data)

      if (e == 'delete') {
        this.toVoid(data)
      } else {
        try {
          const RES = await ProductApi.getProductDatils(data.id)
          console.log(RES, '=============X详情参数')
          const params = RES.data
          if (RES.code === 200) {
            this.rowData = {
              ...RES.data,
              product_barcodes: params.product_barcodes || [{ custom_code_name: '', custom_code: '' }],
              shops: params.product_shops || [{ shop_sku: '', shop_code: '' }],
              isAdd: 'edit',
              // picture_url: []
              picture_url: [
                {
                  id: data.id,
                  display: params.picture_url,
                  src: params.picture_url,
                },
              ],
            }

            this.rowData.is_battery = params.is_battery == false ? '0' : '1'
            this.rowData.is_liquid = params.is_liquid == false ? '0' : '1'
            this.rowData.is_magnetized = params.is_magnetized == false ? '0' : '1'
            this.rowData.category_id = params.category_ids
            console.log(this.rowData.category_id, params.category_ids)
            this.showModel = true
          }
        } catch (error) {
          console.log(error, '获取详情失败')
        }
      }
    },

    OtherFu(e) {
      if (e == 'export') {
        this.$confirm('确定导出产品信息？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          this.confirmExport()
        })
      } else if (e == 'upload') {
        this.showUpload = true
      } else if (e == 'editable') {
        this.showEditTable = true
      }
    },

    async getListDataHandler() {
      const { curr_page, page_size } = this.pagingInfo
      let params = {
        curr_page,
        page_size,
        type: 1,
      }
      params = this.filterSearchData(params)
      try {
        this.loadings = true
        const RES = await ProductApi.getProductList(params)
        console.log(RES.data)
        const { total = 0, records = [] } = RES.data || {}
        this.tableDataList = records
        this.pagingInfo.total = total
        this.selectIds = []
        this.loadings = false
      } catch (error) {
        console.log(error)
        this.loadings = false
        this.$message({
          message: '网络异常/请稍后重试',
          type: 'warning',
        })
      }
    },

    filterSearchData(params) {
      const data = getTruthyParams(this.searchInfo)

      if (data.times && data.times.length) {
        const [begin_time, end_time] = data.times
        params.begin_time = begin_time
        params.end_time = end_time
        delete data.times
      }
      return { ...data, ...params }
    },
  },

  mounted() {
    this.getListDataHandler()
  },
}
</script>
